package com.dnjn.mes.config;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.flyway.FlywayProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

/**
 * FlywayAutoConfiguration
 */
//@DependsOn({"flyway", "flywayInitializer"})
@Slf4j
@Configuration
@ConditionalOnMissingBean({Flyway.class})
@EnableConfigurationProperties({FlywayProperties.class})
public class FlywayConfig {
    @Autowired
    private DataSource dataSource;

    @Autowired
    private FlywayProperties properties;

    @PostConstruct
    public void migrate() {
        Flyway flyway = flyway();
        flyway.migrate();
    }

    @Bean
    public Flyway flyway() {
        return Flyway.configure()
                .dataSource(dataSource)
                .locations(properties.getLocations().toArray(String[]::new))
                .baselineVersion(properties.getBaselineVersion())
                .table(properties.getTable())
                .baselineOnMigrate(true)
                .validateMigrationNaming(true)
                .cleanDisabled(true) //因为这个参数默认是false，默认允许clean schema
                //.cleanOnValidationError(false)
                .ignoreFutureMigrations(true)
                .load();
    }
}
